package com.piece.spider.controller;

import com.piece.core.framework.constant.ExceptionConstants;
import com.piece.core.framework.annotation.permission.AclPermission;
import com.piece.core.framework.annotation.permission.SubmitPermission;
import com.piece.core.framework.support.bootstrap.DataTable;
import com.piece.core.framework.support.bootstrap.QueryTable;
import com.piece.core.framework.support.bootstrap.Valid;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.framework.util.file.FileUtil;
import com.piece.core.web.controller.FrameWorkController;
import com.piece.module.file.util.excel.ExcelParam;
import com.piece.module.file.util.excel.ExcelUtil;
import com.piece.module.spider.dto.SearchRuleDTO;
import com.piece.module.spider.model.SearchRule;
import com.piece.module.spider.service.MagnetSearchService;
import com.piece.module.spider.support.MagnetResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

@RestController
@Api(tags = {"聚合搜索管理"})
@RequestMapping("/api/search/magnet")
public class MagnetController extends FrameWorkController {

    @Resource
    private MagnetSearchService magnetSearchService;

    @PostMapping("/list")
    @AclPermission(code = "spider:rule:view")
    @ApiOperation(value = "查询搜索引擎列表")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public AjaxResponse list() {
        QueryTable queryTable = initTable();
        DataTable dataTable = magnetSearchService.findPage(queryTable);
        return success(dataTable.getData());
    }

    @PostMapping("/table")
    @AclPermission(code = "spider:rule:view")
    @ApiOperation(value = "查询搜索引擎分页数据")
    @ApiImplicitParam(value = "搜索引擎", dataTypeClass = QueryTable.class, type = "body")
    public AjaxResponse table() {
        QueryTable queryTable = initTable();
        DataTable dataTable = magnetSearchService.findPage(queryTable);
        return success(dataTable);
    }

    @GetMapping("/load")
    @AclPermission(code = "spider:rule:view")
    @ApiOperation(value = "加载搜索引擎表单数据")
    @ApiImplicitParam(name = "id", value = "主键ID")
    public AjaxResponse load() {
        Long id = Convert.toLong(getRequest().getParameter("id"));
        if (null == id) {
            return success(new SearchRule());
        }
        SearchRule searchRule = magnetSearchService.findById(id);
        return success(searchRule);
    }

    @SubmitPermission
    @PostMapping("/save")
    @AclPermission(code = "spider:rule:add,spider:rule:edit")
    @ApiOperation(value = "保存搜索引擎表单")
    @ApiImplicitParam(value = "搜索引擎", dataTypeClass = SearchRule.class, type = "body")
    public AjaxResponse save() {
        try {
            SearchRule searchRule = magnetSearchService.findById(Convert.toLong(getRequest().getParameter("id"), 0L));
            if (null == searchRule) {
                // 新增
                searchRule = new SearchRule();
            }
            initDB(searchRule);
            searchRule.setCreateTime(new Date());
            magnetSearchService.insertOrUpdate(searchRule);
            return success(I18nUtil.message(ExceptionConstants.SAVE_SUCCESS), null);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SAVE_FAILURE), e.getMessage());
        }
    }

    @SubmitPermission
    @PostMapping("/delete")
    @AclPermission(code = "spider:rule:delete")
    @ApiOperation(value = "删除搜索引擎")
    @ApiImplicitParam(name = "ids", value = "搜索引擎ID")
    public AjaxResponse delete() throws Exception {
        String ids = getRequest().getParameter("ids");
        if (StringUtil.isNotEmpty(ids)) {
            magnetSearchService.delete(Convert.toLongArray(ids));
        }
        return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS), null);
    }

    @SubmitPermission
    @PostMapping("/search")
    @AclPermission(code = "spider:rule:view")
    @ApiOperation(value = "聚合搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", value = "关键词"),
            @ApiImplicitParam(name = "page", value = "页数"),
            @ApiImplicitParam(name = "rules", value = "规则ID")
    })
    public AjaxResponse search() throws Exception {
        String keyword = getRequest().getParameter("keyword");
        String page = getRequest().getParameter("page");
        String rules = getRequest().getParameter("rules");
        List<MagnetResult> results = magnetSearchService.search(rules, keyword, page);
        return success(results);
    }

    @SubmitPermission
    @PostMapping("/rule/export")
    @AclPermission(code = "spider:rule:export")
    @ApiOperation(value = "导出搜索引擎规则文件")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public AjaxResponse exportRule() {
        try {
            QueryTable queryTable = initTable();
            DataTable dataTable = magnetSearchService.findPage(queryTable);
            List<SearchRule> list = dataTable.getData();
            ExcelParam param = ExcelParam.builder()
                    .sheetName("搜索引擎")
                    .convertType(SearchRuleDTO.class)
                    .data(list)
                    .build();
            InputStream is = ExcelUtil.write(param);
            String fileName = "[搜索引擎列表]_" + FileUtil.generateUniqFileName(getRequest()) + ".xlsx";
            String filePath = FileUtil.getTempPath() + File.separator + fileName;
            FileUtil.writeByteArrayToFile(new File(filePath), FileUtil.toByte(is));
            return success(filePath);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.DOWNLOAD_ERROR), e.getMessage());
        }
    }

    @GetMapping("/rule/checkUnique")
    @ApiOperation(value = "检查引擎是否重复")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "引擎规则ID"),
            @ApiImplicitParam(name = "name", value = "引擎规则名称"),
            @ApiImplicitParam(name = "url", value = "引擎规则地址")
    })
    public Valid checkRuleUnique() {
        Long id = Convert.toLong(getRequest().getParameter("id"));
        String name = getRequest().getParameter("name");
        String url = getRequest().getParameter("url");
        boolean result = true;
        Valid valid = new Valid();
        if (StringUtil.isNotEmpty(name)) {
            result = magnetSearchService.checkNameUnique(id, name);
        } else if (StringUtil.isNotEmpty(url)) {
            result = magnetSearchService.checkUrlUnique(id, url);
        }

        valid.setValid(result);
        return valid;
    }
}
